package com.educationx;

import com.util.PreferenceConnector;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Messenger;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class LoginActivity extends Activity {

	EditText editTextEmail;
	EditText editTextPassword;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);

		editTextEmail = (EditText) findViewById(R.id.editTextUsername);
		editTextPassword = (EditText) findViewById(R.id.editTextPassword);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.login, menu);
		return true;
	}

	public void onGoToMain(View view) {
		Intent intent_login_service = new Intent(getApplicationContext(), LoginService.class);
		Messenger messenger = new Messenger(handler);

		intent_login_service.putExtra("messenger", messenger);
		intent_login_service.putExtra("email", editTextEmail.getText().toString());
		intent_login_service.putExtra("password", editTextPassword.getText().toString());

		startService(intent_login_service);
	}

	private Handler handler = new Handler() {

		public void handleMessage(Message message) {
			if(message.obj == null) {
				Toast.makeText(getApplicationContext(), "Couldn't get course detail. Servers are temporarily " +
						" down.", Toast.LENGTH_LONG).show();
			}
			else if(message.obj.toString().equals("-1\n")) {
				Toast.makeText(getApplicationContext(), "Failed to login. Please check your login " +
						"information.", Toast.LENGTH_LONG).show();
			} else {
				PreferenceConnector.writeString(getApplicationContext(), "id", message.obj.toString().trim());
				Intent i = new Intent(LoginActivity.this, MainActivity.class);
				startActivity(i);
			}
		}
	};
}
